﻿using System;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using DevExpress.Xpo;
using DevExpress.Xpo.Services;

namespace Demo.Service
{
    [ConnectionString("ConnectionString")]
    public class DataService : XpoDataService
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }

        public override void RegisterClasses(XpoProviderMetadata metadata)
        {
            base.RegisterClasses(metadata);

            var type = typeof(PersistentBase);
            var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsAssignableFrom(p));
            
            foreach (Type baseObject in types)
            {
                if (!baseObject.FullName.Contains("DevExpress"))
                {
                    metadata.RegisterEntity(baseObject);
                }
            }
        }

        protected override void OnStartProcessingRequest(ProcessRequestArgs args)
        {
            base.OnStartProcessingRequest(args);
        }

        protected override void HandleException(HandleExceptionArgs args)
        {
            base.HandleException(args);
        }
    }
}
